﻿namespace lighttool.Native
{
    export class canvasAdapter
    {
        static CreateScreenCanvas(canvas: HTMLCanvasElement,width:number=320,height:number=240): spriteCanvas
        {
            //这个尺寸是画布大小，我们采用固定画布大小
            canvas.width = width;//el.clientWidth;
            canvas.height = height;//el.clientHeight;
            var webgl = <WebGLRenderingContext>canvas.getContext('webgl') || <WebGLRenderingContext>canvas.getContext("experimental-webgl");

            var el = webgl.canvas as HTMLCanvasElement;


            var c = new spriteCanvas(webgl, webgl.drawingBufferWidth, webgl.drawingBufferHeight);
            //var asp = range.width / range.height;
            c.spriteBatcher.matrix = new Float32Array([
                1.0 * 2 / c.width, 0, 0, 0,//去掉asp的影响
                0, 1 * -1 * 2 / c.height, 0, 0,
                0, 0, 1, 0,
                -1, 1, 0, 1
            ]);
            c.spriteBatcher.ztest = false;//最前不需要ztest

            setInterval(() =>
            {
                webgl.viewport(0, 0, webgl.drawingBufferWidth, webgl.drawingBufferHeight);
                webgl.clear(webgl.COLOR_BUFFER_BIT | webgl.DEPTH_BUFFER_BIT);
                webgl.clearColor(1.0, 0.0, 1.0, 1.0);

                c.spriteBatcher.begindraw();

                c.userAction?.ondraw(c);

                c.spriteBatcher.enddraw();

                webgl.flush();

            }, 20);
            //那实际上就不存在这种情况
            // window.addEventListener("resize", () =>
            // {
            //     var el = webgl.canvas as HTMLCanvasElement;
            //     // el.width = el.clientWidth;
            //     // el.height = el.clientHeight;
            //     // el.width = el.clientWidth;
            //     // el.height = el.clientHeight;
            //     //采用固定画布尺寸
            //     el.width=512;
            //     el.height=256;

            //     c.width = el.width;
            //     c.height = el.height;
            //     c.spriteBatcher.matrix = new Float32Array([
            //         1.0 * 2 / c.width, 0, 0, 0,//去掉asp的影响
            //         0, 1 * -1 * 2 / c.height, 0, 0,
            //         0, 0, 1, 0,
            //         -1, 1, 0, 1
            //     ]);
            //     ////do resize func
            //     ua.onresize(c);
            // });

            el.onmousemove = (ev: MouseEvent) =>
            {
                c.userAction?.onpointevent(c, canvaspointevent.POINT_MOVE, ev.offsetX, ev.offsetY);
            };
            el.onmouseup = (ev: MouseEvent) =>
            {
                c.userAction?.onpointevent(c, canvaspointevent.POINT_UP, ev.offsetX, ev.offsetY);
            };
            el.onmousedown = (ev: MouseEvent) =>
            {
                c.userAction?.onpointevent(c, canvaspointevent.POINT_DOWN, ev.offsetX, ev.offsetY);
            };


            return c;
        }


    }

}